#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char** argv) {
    if (argc != 4) {
        printf("Usage: rstrip <input-file> <output-file> <mode>\n");
        printf("Mode can be either CRLF or LF\n");
    }
    else {
        FILE* input_file = fopen(argv[1], "rb");
        if (input_file == NULL) {
            perror("Unable to open input file: ");
            exit(1);
        }
        FILE* output_file = fopen(argv[2], "wb");
        if (output_file == NULL) {
            perror("Unable to open output file: ");
            fclose(input_file);
            exit(1);
        }
        char* mode = argv[3];
        if (strcmp(mode, "CRLF") == 0) {
            /*
            CRLF mode
            */
            printf("Now entering CRLF mode...\n");
            int current_char = fgetc(input_file);
            while (current_char != -1) {
                int next_char = fgetc(input_file);
                if (next_char == '\r') {
                    int next_next_char = fgetc(input_file);
                    if (next_next_char == '\n') {
                        fputs("\r\n", output_file);
                        current_char = fgetc(input_file);
                        continue;
                    }
                }
                fputc(current_char, output_file);
                current_char = next_char;
            }
        }
        else if (strcmp(mode, "LF") == 0) {
            /*
            LF mode
            */
            printf("Now entering LF mode...\n");
            int current_char = fgetc(input_file);
            while (current_char != -1) {
                int next_char = fgetc(input_file);
                if (next_char == '\n') {
                    fputc('\n', output_file);
                    current_char = fgetc(input_file);
                    continue;
                }
                fputc(current_char, output_file);
                current_char = next_char;
            }
        }
        else {
            printf("Unrecognized mode. Should be either CRLF or LF.\n");
        }
        fclose(input_file);
        fclose(output_file);
    }
    return 0;
}
